import { ref, reactive, toRefs, onMounted, nextTick, onActivated } from 'vue'

import { onBeforeRouteLeave } from 'vue-router'

export function CommonPage(pathRoot: any, $router: any, $store: any, instance: any) {
  const datas = reactive<{ [key: string]: any }>({
    searchValue: '',
    activeTab: 'saved',
    tabs: [
      { title: '已保存', name: 'saved' },
      { title: '全部', name: 'all' }
    ],
    listReLoad: false // 是否需要重新加载列表
  })
  const listRefs: {
    [key: string]: any
  } = {}
  const setListRef = (el: any, name: string) => {
    if (el) {
      listRefs[name] = el
    }
  }
  const onSearch = () => {
    // 搜索
    tabOnChange()
  }
  const onClear = () => {
    // 搜索
    tabOnChange()
  }
  const onCreate = (type: any) => {
    let query = {}
    if (type && typeof type === 'string') {
      query = { type }
    }
    $router.push({
      path: `/${pathRoot}/add`,
      query
    })
  }
  const tabOnChange = () => {
    nextTick(() => {
      listRefs[`${datas.activeTab}`] && listRefs[`${datas.activeTab}`].resetPageData()
    })
  }
  onMounted(() => {})
  onBeforeRouteLeave((to, from, next) => {
    const instanceName = instance?.type?.name
    if (to.name === 'Index') {
      $store.commit('routerKeep/removeCache', instanceName)
    } else {
      $store.commit('routerKeep/resetCache', instanceName)
    }
    next()
  })

  const { proxy }: any = instance
  proxy.$SimpleEvents.registerEvent('refreshCustomerChangeList', () => {
    datas.listReLoad = true
  })
  proxy.$SimpleEvents.registerEvent('refreshCustomerChangeItem', (id: any) => {
    if (!id) return
    listRefs[`${datas.activeTab}`] && listRefs[`${datas.activeTab}`].refreshItem(id)
  })

  onActivated(() => {
    // 缓存路由才生效
    if (datas.listReLoad) {
      listRefs[`${datas.activeTab}`] && listRefs[`${datas.activeTab}`].resetPageData()
    }
    datas.listReLoad = false
  })

  return {
    datas,
    onSearch,
    onClear,
    onCreate,
    tabOnChange,
    setListRef
  }
}
